<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <!-- 
            inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
            根节点3   左子树中序[9]   右子树中序[15,20,7]
                         左后序[9]    右后序[15,7,20]
            因此右子树根节点20    左中[15]   右中[7]
            //注意啊，leedcode必须return null
         -->
        <script>
            var buildTree = function (inorder, postorder) {
                if (!postorder.length) return null
                let root = {
                    val: postorder[postorder.length - 1],
                    left: null,
                    right: null,
                }
                //找出根节点位置，从而找出左右子树   [9]   [15,20,7]  后序是[9] [15,7,20]
                let mid = inorder.indexOf(root.val)
                root.left = buildTree(inorder.slice(0, mid), postorder.slice(0, mid))
                root.right = buildTree(inorder.slice(mid + 1), postorder.slice(mid, postorder.length - 1))
                return root
            }
            console.log(buildTree([9, 3, 15, 20, 7], [9, 15, 7, 20, 3]))
        </script>
    </body>
</html>
